/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ch.repit.aglaja.client.contacts;

import ch.repit.rwt.client.AttributeType;
import ch.repit.rwt.client.Bento;
import ch.repit.rwt.client.BentoAttribute;
import ch.repit.rwt.client.BentoStatus;
import ch.repit.rwt.client.ObjectRef;
import ch.repit.rwt.client.logs.LogManager;
import ch.repit.rwt.client.pdf.StickersPrintingPage;
import ch.repit.rwt.client.persistence.CacheManager;
import ch.repit.rwt.client.security.Action;
import ch.repit.rwt.client.security.SecurityManager;
import ch.repit.rwt.client.ui.Page;
import ch.repit.rwt.client.ui.form.BooleanDropDownField;
import ch.repit.rwt.client.ui.form.DateField;
import ch.repit.rwt.client.ui.form.FieldRow;
import ch.repit.rwt.client.ui.form.FieldValidator;
import ch.repit.rwt.client.ui.form.FileTable;
import ch.repit.rwt.client.ui.form.FileUploadField;
import ch.repit.rwt.client.ui.form.FormPage;
import ch.repit.rwt.client.ui.form.RegexpFieldValidator;
import ch.repit.rwt.client.ui.form.SelectField;
import ch.repit.rwt.client.ui.form.TextField;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.ButtonBase;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.PushButton;
import com.google.gwt.user.client.ui.Widget;
import java.util.List;


/**
 *
 * @author tc149752
 */
public class PersonTab extends FormPage {

    private ObjectRef addressRef;

    private FileTable filePage;

    public PersonTab(ObjectRef personRef, Page topPage)
    {
        super(PersonDef.TYPE, personRef, topPage);
    }
    

    /**
     * Used when new persons are created
     */
    public PersonTab(ObjectRef addressRef)
    {
        super(PersonDef.TYPE, null, null);
        this.addressRef = addressRef;
    }
    

    @Override
    protected void init() {

        if (isCreate()) {
            setTitle("Création personne");
        }
        else {
            setTitle(getObject().getDisplayValue(PersonDef.ATTR_FIRSTNAME));
        }
        super.setShowPath(true);

        // name
        TextField firstName = new TextField(PersonDef.ATTR_FIRSTNAME, "prénom");
        TextField lastName = new TextField(PersonDef.ATTR_LASTNAME, "nom de famille");
       
        FieldRow nameRow = new FieldRow("Nom");
        nameRow.addField(firstName);
        nameRow.addField(lastName);
        this.addFieldRow(nameRow);

        // mail and phones
        this.addSectionHead("Contact");
        TextField email = new TextField(PersonDef.ATTR_EMAIL);
        email.setColumns(45);
        email.addValidator(new RegexpFieldValidator
                ("^[\\w._%+-]+@[\\w.-]+\\.[a-zA-Z]{2,6}$" , "L'email est invalide"));
        this.addSingleFieldRow("E-mail", null, email);

        FieldValidator phoneValidator = new RegexpFieldValidator("^[\\+\\d][\\d ]{9,16}$",
                        "Numéro invalide, veuillez ne saisir que des chiffres et des espace, et éventuellement un '+' en tête.");
        TextField mobile = new TextField(PersonDef.ATTR_MOBILEPHONE, "natel");
        mobile.addValidator(phoneValidator);
        mobile.setColumns(20);
        TextField prof = new TextField(PersonDef.ATTR_PROFPHONE, "prof.");
        prof.addValidator(phoneValidator);
        prof.setColumns(20);
        FieldRow phone1 = new FieldRow("Téléphones");
        phone1.addField(mobile);
        phone1.addField(prof);
        phone1.setHelp("Uniquement des chiffres et des espaces");
        this.addFieldRow(phone1);

        //
        this.addSectionHead("Divers");
        DateField dob = new DateField(PersonDef.ATTR_DATEOFBIRTH);
        this.addSingleFieldRow("Date de Naissance", null, dob);
        BooleanDropDownField sex = new BooleanDropDownField(PersonDef.ATTR_ISMALEGENDER, null, "Homme", "Femme", "-");
        this.addSingleFieldRow("Sexe", null, sex);

        // picture
        this.addSectionHead("Photo");
        if (SecurityManager.get().getAuthorizer().isAllowed(Action.UPDATE, getObject())) {
            FileUploadField fuf = new FileUploadField("emplacement local", this);
            this.addSingleFieldRow("Envoyer une nouvelle photo",
                    "Veuillez spécifier l'emplacement local (sur votre ordinateur) d'un fichier de type image (jpeg, png, gif, etc), puis cliquer sur Transférer. Attention, l'image précédente sera perdue.",
                    fuf);
        }

        filePage = new FileTable(this);
        Widget table = filePage.getTable();
        table.addStyleName("rwt-formAttributePanel");
        super.addWidgetRow("Photo actuelle", null, table);

        super.init();
    }


    @Override
    public void setObject(Bento bento) {
        super.setObject(bento);
        filePage.resetBento(bento);
    }
    

    @Override
    protected void fillToolbarWidgets(List<Widget> leftWidgets,
                                      List<Widget> middleWidgets,
                                      List<Widget> rightWidgets) {
        super.fillToolbarWidgets(leftWidgets, middleWidgets, rightWidgets);

        if (!isCreate()) {
            // if only person, disable delete button
            Bento person = getObject();
            Bento address = CacheManager.get().getCachedObject(person.getDisplayValue(PersonDef.ATTR_ADDRESSREF));
            boolean alone = true;
            for (Bento b : CacheManager.get().getCachedObjects(PersonDef.TYPE)) {
                if ( b.getStatus()==address.getStatus()
                        && address.getRef().toString().equals(b.getDisplayValue(PersonDef.ATTR_ADDRESSREF))
                        && !b.getRef().equals(person.getRef()) )  {
                    alone = false;
                }
            }
            if (alone) {
                for (Widget w : leftWidgets) {
                    if (w instanceof ButtonBase) {
                        ButtonBase but = (ButtonBase)w;
                        if ("Supprimer".equals(but.getText()))
                            but.setEnabled(false);
                    }
                }
            }
            else {
                // leaves this address to go in a new address
                Hyperlink h = new Hyperlink("Déménage (nouvelle adresse)","movesOutNewAddress");
                h.addClickHandler( new ClickHandler() {
                    public void onClick(ClickEvent event) {
                        getPageNav().displayPage(new NewAddressPage(getObject().getRef()));
                    }
                });
                middleWidgets.add(h);
            }

            // if person is trashed and address as well, disable untrash button, as the whole address must be untrashed
            if (person.getStatus().equals(BentoStatus.TRASH)
                    && address.getStatus().equals(BentoStatus.TRASH)) {
                for (Widget w : leftWidgets) {
                    if (w instanceof ButtonBase) {
                        ButtonBase but = (ButtonBase)w;
                        if ("Récupérer".equals(but.getText()))
                            but.setEnabled(false);
                        else if ("Effacer définitivement".equals(but.getText()))
                            but.setEnabled(false);
                    }
                }
            }

            // leave this address to go in another existing address
            if (getObject().getStatus() == BentoStatus.ACTIVE) {
                // leaves this address to go in a new address
                Hyperlink h = new Hyperlink("Déménage (adresse définie)","movesOutExistAddress");
                h.addClickHandler( new ClickHandler() {
                    public void onClick(ClickEvent event) {
                        getPageNav().displayInPopup(new MoveToExistingAddress(getObject().getRef()),true);
                    }
                });
                middleWidgets.add(h);
            }

            if (getObject().getStatus() == BentoStatus.ACTIVE) {
                PushButton stickers = new PushButton("Etiquette personnelle");
                stickers.addClickHandler(new ClickHandler() {
                    public void onClick(ClickEvent arg0) {
                        getPageNav().displayInPopup(new StickersPrintingPage(null,getObject().getRef()), true);
                    }
                });
                rightWidgets.add(stickers);
            }
        }

    }




    @Override
    public void doSave(Bento bento) {
        if (addressRef != null) {
            BentoAttribute hha = new BentoAttribute(PersonDef.ATTR_ADDRESSREF, AttributeType.STRING);
            hha.set(addressRef.toString());
            bento.put(PersonDef.ATTR_ADDRESSREF, hha);
        }
        super.doSave(bento);
    }

    
    /**
     * overriden in order not to perform the back...
     * @param objectRef
     */
    @Override
    protected void doSaveOnSuccess(ObjectRef objectRef) {
        LogManager.get().handled("Enregistrement terminé.");
        CacheManager.get().refreshCache();

        // performs the back only when the page was used for user cretion from an address page
        if (addressRef!=null)
            getPageNav().back();
    } 


    
    class MoveToExistingAddress extends FormPage {

        public MoveToExistingAddress(ObjectRef personRef) {
            super(PersonDef.TYPE, personRef, null);

            setTitle("Déménagement vers adresse existante");
            setShowPath(false);
            setPageEdited();
            setOnlyTopToolbar(true);
            // hide comments?

            // adress select box
            SelectField newAddress = new SelectField(PersonDef.ATTR_ADDRESSREF, false);
            newAddress.setValueMap(AddressUtil.getAddressesSelectMap());

            this.addSingleFieldRow("Nouvelle adresse", null, newAddress);
        }

        @Override
        protected void fillToolbarWidgets(List<Widget> leftWidgets,
                                      List<Widget> middleWidgets,
                                      List<Widget> rightWidgets) {
            super.fillToolbarWidgets(leftWidgets, middleWidgets, rightWidgets);

            Widget toRemove = null;
            for (Widget w : leftWidgets) {
                if (w instanceof ButtonBase) {
                    ButtonBase b = (ButtonBase)w;
                    if (b.getText().equals("Supprimer"))
                        toRemove = b;
                }
            }
            if (toRemove != null)
                leftWidgets.remove(toRemove);
        }



        // if last one at old address, trash / suppress it...
        @Override
        protected void doSaveOnSuccess(ObjectRef personRef) {
            String addressRef = CacheManager.get().getCachedObject(personRef).getDisplayValue(PersonDef.ATTR_ADDRESSREF);
            boolean alone = true;
            for (Bento b : CacheManager.get().getCachedObjects(PersonDef.TYPE)) {
                if ( addressRef.equals(b.get(PersonDef.ATTR_ADDRESSREF).getString())
                        && !b.getRef().equals(personRef)) {
                    alone = false;
                }
            }
            if (alone) {
                Bento address = CacheManager.get().getCachedObject(addressRef);
                // trash or perm delete?
                super.doPermanentDelete(address);
            }

            getPageNav().closePopup();
            super.doSaveOnSuccess(objectRef);
        }



    }


}
